import { EOL } from 'node:os';
import { existsSync, unlinkSync, createWriteStream } from 'node:fs';
import { resolve, relative, parse, format as _format } from 'node:path';
import { globSync } from 'glob';
import { defineConfig } from 'rollup';

import cleanPlugin from './plugin/cleanDir.js';
import copyReleaseFilePlugin from './plugin/copyReleaseFile.js';

export default async ({
    inputDir,
    outputDir,
    excludeFiles,
    extarnalDirname
}) => {
    const inputExt = '.ts',
        mainInputFilePath = resolve(inputDir, 'index.ts');
    if (existsSync(mainInputFilePath)) unlinkSync(mainInputFilePath);

    const mainFileWriteStream = createWriteStream(mainInputFilePath);
    const input = globSync(`${inputDir}/**/*${inputExt}`)
        .map((file) => {
            const filePath = relative('src', file);
            if (!excludeFiles.includes(filePath)) {
                mainFileWriteStream.write(
                    `export * from './${filePath.replaceAll(inputExt, '')}';` +
                        EOL
                );
                return resolve(inputDir, filePath);
            }
        })
        .filter((p) => p);
    mainFileWriteStream.end();

    return defineConfig([
        {
            input,
            treeshake: {
                moduleSideEffects: false
            },
            output: [
                {
                    dir: outputDir,
                    format: 'module',
                    hoistTransitiveImports: false,
                    manualChunks(id) {
                        if (id.includes('node_modules'))
                            return `${extarnalDirname}/vendor`;
                        return null;
                    },
                    entryFileNames(option) {
                        const ext = '.js';
                        const basePath = relative(
                            inputDir,
                            option.facadeModuleId
                        );
                        const parser = parse(basePath);
                        return _format({
                            root: '',
                            dir: parser.dir,
                            base: parser.name + ext,
                            ext
                        });
                    }
                }
            ],
            plugins: [cleanPlugin()]
        },
        {
            input: mainInputFilePath,
            output: {
                name: 'mvcommon',
                format: 'umd',
                file: resolve(outputDir, 'index.js'),
                hoistTransitiveImports: false
            },
            plugins: [copyReleaseFilePlugin()]
        }
    ]);
};
